import { Ref } from 'vue';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

export function useThreeJS(canvasRef: Ref<HTMLCanvasElement | null>) {
  let scene: THREE.Scene;
  let camera: THREE.PerspectiveCamera;
  let renderer: THREE.WebGLRenderer | null = null;
  let controls: OrbitControls | null = null;
  let animationId: number = 0;
  let cube: THREE.Mesh;

  const init = () => {
    if (!canvasRef.value) return;

    // 初始化场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xcccccc);
    
    // 初始化相机
    camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
    camera.position.set(0, 12, 5);
    camera.lookAt(0, 0, 0);
    
    // 初始化渲染器
    renderer = new THREE.WebGLRenderer({ 
      canvas: canvasRef.value,
      antialias: true 
    });
    renderer.setSize(500, 500);
    
    // 创建立方体
    const geometry = new THREE.BoxGeometry(4, 4, 4);
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
    
    // 初始化控制器
    controls = new OrbitControls(camera, canvasRef.value);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    
    // 开始动画
    animate();
  };

  const animate = () => {
    if (!renderer) return;
    
    animationId = requestAnimationFrame(animate);
    controls?.update();
    renderer.render(scene, camera);
  };

  const cleanup = () => {
    if (animationId) {
      cancelAnimationFrame(animationId);
    }
    controls?.dispose();
    renderer?.dispose();
  };

  return {
    init,
    cleanup
  };
}